<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox, ElPagination} from 'element-plus'
import addUnits from "@/components/Unit/AddDialog.vue"
import updateUnit from "@/components/Unit/UpdateDialog.vue"
import {deleteUnit, getPageUnits} from "@/apis/zyj/units.js";

const allUnits = reactive([])
const tableData = reactive([])
//显示添加对话框
const addDialogs = ref(false)
//修改对话框
const updateDialog = ref(false)
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理
const searchForm = reactive({
  unitCode: '',
  unitName: ''
})

//获取表格数据
function initTableData() {
  getPageUnits(searchForm.unitCode, searchForm.unitName, currentPage.value, pageSize.value).then(res => {
    tableData.length = 0
    tableData.push(...res.records);
    total.value = res.total;
    currentPage.value = res.current;
  })
}

function getAllUnit() {
  getPageUnits('', '', -1, -1).then(resp => {
    if (resp != null) {
      allUnits.length = 0;
      Object.assign(allUnits, resp)
    }
  })
}

//初始化数据
onMounted(() => {
  initTableData()
  getAllUnit()
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const onSearch = () => {
  initTableData()
}

const onReset = () => {
  searchForm.unitCode = ''
  searchForm.unitName = ''
}

const onAdd = () => {
  addDialogs.value = true;
}

const onModify = (row) => {
  if (row.id != null) {
    multipleSelection.value = {...row}
  } else {
    multipleSelection.value = {...multipleSelection.value[0]}
  }
  console.log(multipleSelection.value)
  updateDialog.value = true;
}

const onDelete = (row) => {
  if (row.id != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.id != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.id)
        }
        deleteUnit(select_orderId.value).then((res) => {
          if (res == '成功') {
            initTableData()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = 0;
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

const getRowKeys = (row) => {
  //记录每行的key值
  return row.id;
}
//选中事件
const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.id);
      }
    });
  }
}

const handleSizeChange = (val) => {
  initTableData()
}

const handleCurrentChange = (val) => {
  initTableData()
}
//关闭添加对话框
const closeDialog = () => {
  addDialogs.value = false;
  updateDialog.value = false;
  initTableData()
  multipleTable.value.clearSelection();
};


</script>

<template>
  <div class="unit-management">
    <el-card>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="单位">
          <el-input v-model="searchForm.unitCode" placeholder="请输入单位编码" clearable/>
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model="searchForm.unitName" placeholder="请输入单位名称" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <div class="action-buttons">
        <el-button type="primary" @click="onAdd" plain>新增</el-button>
        <el-button type="warning" @click="onModify" :disabled="select_order_number!=1" plain>修改</el-button>
        <el-button type="danger" @click="onDelete" :disabled="select_order_number==0" plain>删除</el-button>
      </div>

      <el-table :data="tableData" ref="multipleTable" @selection-change="handleSelectionChange"
                :row-style="{height: '60px'}" max-height="380px" style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="unit" label="单位编码"/>
        <el-table-column prop="unitName" label="单位名称"/>
        <el-table-column prop="isMainUnit" label="是否是主单位">
          <template #default="scope">
            <el-tag :type="scope.row.isPrimaryUnit == '0'  ? 'success' : 'info'">
              {{ scope.row.isPrimaryUnit == '0' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="conversionRatio" label="与主单位换算比例"/>
        <el-table-column prop="isEnabled" label="是否启用">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled =='0' ? 'success' : 'info'">
              {{ scope.row.isEnabled == '0' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注"/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button link size="small" type="primary" @click="onModify(scope.row)">修改</el-button>
            <el-button link size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:currentPage="currentPage"
            v-model:pageSize="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <add-units :addDialog="addDialogs" :allUnits="allUnits" @close-dialog="closeDialog"/>
    <update-unit :allUnits="allUnits" :updateDialog="updateDialog" :form="multipleSelection"
                 @close-dialog="closeDialog"/>
  </div>
</template>


<style scoped>
.unit-management {
  padding: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: left;
}

.el-pagination {
  justify-content: flex-end;
}

</style>
